package dk.suaq.halfdoneprojects.server;

import javax.jdo.JDOHelper;
import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.PersistenceManagerFactory;

public class AbstractDao<C> {
	
	private static final PersistenceManagerFactory pmfInstance = JDOHelper
			.getPersistenceManagerFactory("transactions-optional");

	protected PersistenceManagerFactory getPersistence() {
		return pmfInstance;
	} 
	
	public C save(C content) {
		PersistenceManager pm = open();
		try {
			return (C) pm.makePersistent(content);
		} finally {
			pm.close();
		}
	}
	
	public C get(String key) {
		PersistenceManager pm = open();
		try {
			return (C) pm.getObjectById(key);
		} 
		catch(JDOObjectNotFoundException e) {
			return null; 
		} 
		finally {
			pm.close();
		}
	}

	private PersistenceManager open() {
		return (PersistenceManager) pmfInstance.getPersistenceManager(); 
	}
}
